﻿using System.Linq.Expressions;

using Tszy.Unlimited.Data.AdoNet.Sql.Components.Expressions.Values;

namespace Tszy.Unlimited.Data.AdoNet.Sql.Components.Expressions
{
    /// <summary>
    /// 表达式执行者。
    /// </summary>
    internal interface IExpressionExecutor
    {
        /// <summary>
        /// 处理名称。
        /// </summary>
        string Name { get; }

        /// <summary>
        /// 执行。
        /// </summary>
        /// <param name="context">上下文。</param>
        /// <param name="expression">表达式。</param>
        /// <returns>结果。</returns>
        ExpressionExecutorResult Execute(ExpressionContext context, Expression expression);
    }

    /// <summary>
    ///
    /// </summary>
    internal abstract class ExpressionExecutorBase : IExpressionExecutor
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        protected ExpressionExecutorBase(string name)
        {
            Name = name;
        }

        /// <summary>
        /// 处理名称。
        /// </summary>
        public string Name { get; }

        /// <summary>
        /// 执行。
        /// </summary>
        /// <param name="context">上下文。</param>
        /// <param name="expression">表达式。</param>
        /// <returns>结果。</returns>
        public abstract ExpressionExecutorResult Execute(ExpressionContext context, Expression expression);

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        protected virtual ExpressionExecutorResult ResultSuccess()
        {
            return new ExpressionExecutorResult { Status = true };
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        protected virtual ExpressionExecutorResult ResultError()
        {
            return new ExpressionExecutorResult { Status = false };
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        protected string GetParameterNameByLambda(ExpressionContext context, Expression expression)
        {
            var lambdaExpression = expression as LambdaExpression;

            var parameter = ValueExpressionHandler.Handler(context, lambdaExpression?.Body);

            return $"{parameter.Value}";
        }
    }
}